package com.gzz.orchid.context.domain.rbac.impl;

import com.gzz.orchid.common.boot.mybatis.conditices.QueryCondition;
import com.gzz.orchid.common.core.authorization.UserContextHolder;
import com.gzz.orchid.context.domain.rbac.IModuleRepository;
import com.gzz.orchid.context.domain.rbac.entity.ModuleDo;
import com.gzz.orchid.context.infrastructure.definition.Status;
import com.gzz.orchid.context.infrastructure.persistence.entity.sys.SysModulePo;
import com.gzz.orchid.context.infrastructure.persistence.mapper.sys.SysModuleMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
/**
 * @author higmd
 */
@Slf4j
@Repository
@RequiredArgsConstructor
public class ModuleRepository implements IModuleRepository {
    private final SysModuleMapper mapper;

    @Override
    public ModuleDo findByCode(String code) {
        var condit = new QueryCondition();
        condit.eq("code", code);
        SysModulePo po = mapper.selectOneByCondition(condit);
        return Optional.ofNullable(po).map(ModuleDo::convertFrom).orElse(null);
    }

    @Override
    public List<ModuleDo> findListByIds(Serializable[] ids) {
        List<SysModulePo> poList = mapper.selectListByIds(ids);
        //
        return poList.stream()
                .map(ModuleDo::convertFrom)
                .collect(Collectors.toList());
    }

    @Override
    public int batchDelete(Serializable[] ids) {
        var n =mapper.removeByIds(ids);
        // 记录日志log
        log.info("删除模块[{}]成功，删除{}行数据", ids, n);
        return n;
    }

    @Override
    public int batchChangeStatus(Status status, List<ModuleDo> doList) {
        var po = new SysModulePo();
        po.setStatus(status.getValue());
        po.setUpdatedOn(LocalDateTime.now());
        po.setUpdatedBy(UserContextHolder.getUserCode());
        // 条件
        var condit = new QueryCondition();
        condit.in("id", doList.stream().map(ModuleDo::getId).toArray());
        var n = mapper.updateByCondition(po, condit);
        // 记录日志log
        log.info("批量修改[{}]模块状态[{}]成功，影响{}行数据", doList.size(), status.getValue(), n);
        return n;
    }

    @Override
    public void save(ModuleDo moduleDo) {
        var po = new SysModulePo();
        var n = (Objects.isNull(po.getId()))? mapper.insert(po): mapper.updateById(po);
        // 记录日志log
        log.info("保存模块[{}]成功，影响{}行数据", moduleDo.getName(), n);
    }
}
